﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;
using System.Diagnostics;
using BAL.EstRec;
using FileOps;
using System.Windows.Threading;
using MasterDetailEx.Notify;
using BAL.EstRec.SYNC;
using System.Data;

namespace MasterDetailEx.Config
{
    /// <summary>
    /// Interaction logic for WndCnfig.xaml
    /// </summary>
    public partial class WndCnfig : Window
    {
        AppConfs Configs ;
        MainWindow mw;

        public WndCnfig()
        {
            InitializeComponent();

            Assembly assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
            lbl_actualVer.Text = fvi.ProductVersion.ToString();
            Configs = new AppConfs();
            setLabels();

            brdNav_sinc_MouseUp(brdNav_sinc, null);
        }

        private void setLabels()
        { 
            try 
	        {
                DataTable dt = Sync.getLastSyncData();
                
                if (dt.Rows.Count>0)
	            {
                    txtUltimaSincCat.Text = dt.Rows[0]["LAST_UPDATE"].ToString();
                    lbl_listZips.Text = dt.Rows[0]["FILE_NAME"].ToString().Split('\\').Last();
	            }

                dt = Sync.getLastCheckupdate();
                if (dt.Rows.Count > 0)
                {
                    lbl_lastUpdate.Text = dt.Rows[0]["CHECK_DATE"].ToString();
                }
		 
	        }
	        catch (Exception ex)
	        {
                txtUltimaSincCat.Text ="";
                lbl_listZips.Text = "";
	        }
        }

        private void brdNav_sinc_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test002");
            this.selectNavItem(((Border)sender).Name);
        }

        private void brdNav_update_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test003");
            this.selectNavItem(((Border)sender).Name);
        }

        private void showElement(string elem)
        {
            Grid grd = (Grid)this.FindName("grdConfOptions");
            foreach (var test in grd.Children)
            {
                if (((Border)test).Name == elem)
                {
                    ((Border)test).Visibility = Visibility.Visible;
                }
                else
                {
                    ((Border)test).Visibility = Visibility.Hidden;
                }

            }
        }

        private void selectNavItem(string navItem)
        {
            foreach (var border in ((StackPanel)this.FindName("spConfigNav")).Children)
            {
                if (((Border)border).Name == navItem)
                {
                    ((Border)border).BorderThickness = new Thickness(5, 0, 0, 0);
                    ((Border)border).BorderBrush = Brushes.Red;

                    BrushConverter bc = new BrushConverter();
                    Brush b;
                    b = (Brush)bc.ConvertFrom("#f9f9f9");
                    ((Border)border).Background = b;
                    //<Setter Property="Background" Value="#f9f9f9"></Setter>
                }
                else
                {
                    ((Border)border).BorderThickness = new Thickness(0, 0, 0, 0);
                    ((Border)border).Background = Brushes.Transparent;
                    ((Border)border).Style = (Style)this.FindResource("ConfNavBorder");
                }
            }
        }

        private void btn_updateVersion_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("¿Desea actualizar la aplicación en este momento?", "Actualización de versión", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                System.Diagnostics.Process.Start(Configs.cnf.CarpetaInstalacion.ToString() + Configs.cnf.UpdaterProcess.ToString());

            }

        }


        private void btnCerrar_Click(object sender, RoutedEventArgs e)
        {
            
            this.Close();
        }

        private void btnSinc_Click(object sender, RoutedEventArgs e)
        {
            this.lblmensaje.Content = "Iniciando sincronización...";
            SyncAction();

            this.Close();
        }

        private void SyncAction()
        {
            FolderSync fs = new FolderSync();
            fs.CatZipPath = Configs.cnf.svrCatZipPath.ToString();
            fs.ClntCatZipPath = Configs.cnf.clntCatZipPath.ToString();
            fs.TmpCatPath = Configs.cnf.tmpCatPath.ToString();
            fs.ClientDataPath = Configs.cnf.clientDataPath.ToString();
            fs.ServerDataPath = Configs.cnf.serverDataFolder.ToString();
            fs.DataFilesFolder = Configs.cnf.dataFilesFolder.ToString();

            fs.FilesProcessedPath = Configs.cnf.ProcessedFilesSync;
            this.mw = (MainWindow)App.Current.MainWindow;

            if (this.mw.ActualUser.ToUpper() == "HQ")
                SyncThread.start(fs, (ISyncEventImp)this.mw, true);
            else
                SyncThread.start(fs, (ISyncEventImp)this.mw, false);

            this.lblmensaje.Content = "";
        }

        public void refreshUi()
        {
            this.mw.nav.loadData();
        }


        #region sync eventHandlers

        public void fs_SyncCompletedEvent(object sender, FolderSyncEventArgs e)
        {

            this.refreshUi();

        }

        public void fs_FileEvent(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                    PopupNotify.start(mw, SyncMsg);

                }));
        }

        public void fs_FileErrorEvent(object sender, FolderSyncEventArgs e)
        {
           // MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                    PopupNotify.start(mw, SyncMsg);

                }));
        }

        public void fs_fileDownloaded(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                //Sync.upsertCatFileStatus(0, 0, fs.FileName, true);
                Sync.upsertCatZipStatus(0, fs.FileName, true, false);

                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(() =>
            {
                //lbl_ad.Content = "sync estatus:" + e.StatSync.Estatus;
                PopupNotify.start(mw, SyncMsg);

            }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message);

            }

        }//

        public void fs_FileUnzippedEvent(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                if (e.FileSync.isCat)
                    Sync.upsertCatZipStatus(0, fs.FileName, true, true);
                if (e.FileSync.isData)
                    Sync.upsertControlTable(0, fs.FileName, "Data", true, false, false);


                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(() =>
            {
                PopupNotify.start(mw, SyncMsg);

            }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message);
            }
        }

        public void fs_FileUploadedEvent(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Estatus: {0},error: {1}", e.FileSync.msg, e.FileSync.Error);
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                if (e.FileSync.isCat)
                    Sync.upsertCatFileStatus(e.FileSync.IdCat, e.FileSync.UnidZip, e.FileSync.FileName, true);
                if (e.FileSync.isData)
                    Sync.upsertControlTable(0, fs.FileName, "Data", true, e.FileSync.isInSTG, e.FileSync.Cargado);

                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error BD: " + ex.Message);
            }
        }

        public void fs_CatStartSyncEvent(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Sync cat automática inicia...");
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex.Message);
            }
        }//

        public void fs_CatEndSyncEvent(object sender, FolderSyncEventArgs e)
        {
            //MainWindow mw = (MainWindow)App.Current.MainWindow;

            Console.WriteLine("Sync cat automática finaliza...");
            string SyncMsg = e.FileSync.msg;

            FolderSync fs = (FolderSync)sender;

            try
            {
                DispatcherOperation dop = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    PopupNotify.start(mw, SyncMsg);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex.Message);
            }
        }//


        #endregion

        
    }//class
}
